<template>
	<div class="activity-list">
		<el-row>
			<el-col :span="6">
				<div class="left-box">
					<el-tabs v-model="box_index_key" @tab-click="handleClick">
						<el-tab-pane v-for="(item, index) in box_list_arr" :key="index" :label="item.label"
							:name="item.name">
							<div class="select-box flex_between">
								<el-select size="mini" class="select-w" v-model="time" placeholder="请选择"
									@change="selectFun">
									<el-option v-for="item in time_data" :key="item.id" :label="item.name"
										:value="item.id">
									</el-option>
								</el-select>
								<el-select size="mini" class="select-w" v-model="shopid_yd" placeholder="请选择"
									@change="selectFun">
									<el-option v-for="item in getYunShopList" :key="item.id" :label="item.name"
										:value="item.id">
									</el-option>
								</el-select>
							</div>
							<template v-if="box_index_key == '-1'">
								<div class="board-box mt10">
									<div class="flex_between">
										<div class="font_size22">数据看板</div>
									</div>
									<div class="">
										<p class="font_size16">累计发放积分</p>
										<div class="" style="line-height: 40px;">
											<span style="font-size: 36px;">{{ jf_total || 0 }}</span>
										</div>
									</div>
								</div>
								<div class="flex_between mt10">
									<h2 class="font_size16">签到规则</h2>
									<el-select size="mini" class="select-w" v-model="statusSt" placeholder="请选择"
										@change="selectFun">
										<el-option v-for="item in getStatusList" :key="item.id" :label="item.name"
											:value="item.id">
										</el-option>
									</el-select>
								</div>
								<div :style="{ height: stateHooks.leftHeight - 260 + 'px', overflow: 'hidden' }">
									<LeftList :height="stateHooks.leftHeight - 260" :templates="templates"
										:listData="listData" :selectedIndex.sync="selectedIndex" @loadFun="loadFun"
										ref="leftListRef" :lLoading="lLoading" :lNoMore="lNoMore"
										@clickItem="clickItem">
										<div slot-scope="{row}" slot="title" class="flex_between">
											<span class="bold">{{ row.title || '-' }}</span>
											<span>{{ row.status_txt || '-' }}</span>
										</div>
										<div slot-scope="{row}" slot="time_txt" class="flex_between">
											<span>{{ row.time_txt || '-' }}</span>
										</div>
									</LeftList>
								</div>
							</template>
							<template v-else>
								<div :style="{ height: stateHooks.leftHeight + 'px', overflow: 'hidden' }">
									<LeftList :height="stateHooks.leftHeight"
										:templates="box_index_key == '1' ? templates : templatesEventLs"
										:listData="listData" :selectedIndex.sync="selectedIndex" @loadFun="loadFun"
										ref="leftListRef" :lLoading="lLoading" :lNoMore="lNoMore"
										@clickItem="clickEventLsItem">
										<div slot-scope="{row}" slot="title" class="flex_between">
											<span class="bold">{{ row.title || '-' }}</span>
										</div>
										<div slot-scope="{row}" slot="time_txt" class="flex_between">
											<span>{{ row.time_txt || '-' }}</span>
										</div>
									</LeftList>
								</div>
							</template>
						</el-tab-pane>
					</el-tabs>
					<div class="iconBox" v-if="box_index_key == '-1'">
						<text class="icon-font search-icon" @click="addActivityList">&#xe606;</text>
					</div>
				</div>
			</el-col>
			<el-col :span="18">
				<div class="rigth-box">
					<!-- 数据看板编辑 新增信息 -->
					<template v-if="box_index_key == '-1'">
						<addOrEdit :getYunShopList="getYunShopSeleteList" ref="addOrEditRef" @backFun="backFun"
							@addTpBmFun="addTpBmFun" :detailID="detailID" :isDisbableInfo="isDisbableInfo"
							:typeLsSys="typeLsSys">
						</addOrEdit>
					</template>
					<!-- 界面详情 -->
					<template v-if="box_index_key == '1'">
						<deviceMobile :getYunShopList="getYunShopSeleteList" ref="addOrEditRef" @backFun="backFun"
							@addTpBmFun="addTpBmFun" :detailID="detailID" :isDisbableInfo="isDisbableInfo"
							:typeLsSys="typeLsSys">
						</deviceMobile>
					</template>
					<template v-else>
						<detaill ref="detaillRef" :detailGiveObj="detailGiveObj">
						</detaill>
					</template>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
import {
	ref,
	onMounted,
	getCurrentInstance,
	watch,
	computed
} from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import {
	statusColor
} from "@/utils/common.js"
import {
	useCommonHooks
} from '@/hooks/useCommonHooks.js'

import LeftList from "@/pages/signIn/components/leftList.vue"
import addOrEdit from "@/pages/signIn/components/addOrEdit.vue"
import deviceMobile from "@/pages/signIn/components/deviceMobile.vue"
import detaill from "@/pages/signIn/components/detaill.vue"

const maxPnum = 20

// 获取当前组件实例
const {
	proxy
} = getCurrentInstance()

// 使用全局状态
const {
	stateHooks
} = useCommonHooks()

const lLoading = ref(false)
const lNoMore = ref(false)

// 如果是编辑页面，设置某些值不能编辑
const isDisbableInfo = ref({
	type: false,
	index_key: '-1',
})

const box_index_key = ref('-1')
const selectedIndex = ref(0)
const recordSelectedIndex = ref(0)
const box_list_arr = ref([{
	label: "数据看板",
	name: '-1',
},
{
	label: "记录",
	name: '2',
}, {
	label: "界面",
	name: '1',
}
])

// 分销明细记录
const templates = ref([{
	type: "slot",
	key: "title",
},
{
	type: "init",
	key: "shop_name",
},
{
	type: "slot",
	key: "time_txt",
},
])

// 分销规则记录
const templatesEventLs = ref([{
	type: "init",
	key: "shop_name",
},
{
	type: "init",
	key: "cname_txt",
},
{
	type: "init",
	key: "v_txt",
},
{
	type: "init",
	key: "atime_txt",
},
])

const listData = ref([])
const detailID = ref('')
const jf_total = ref(0)

const statusSt = ref('0')
const getStatusList = ref([])

const getYunShopList = ref([])
const getYunShopSeleteList = ref([])

const time_data = ref([{
	id: 0,
	name: "全部日期",
},
{
	id: "1",
	name: "今日",
},
{
	id: "2",
	name: "本月",
},
{
	id: "3",
	name: "本季",
},
{
	id: "4",
	name: "本年",
},
{
	id: "23",
	name: "近3月",
},
{
	id: "26",
	name: "近6月",
}
])

const time = ref(0)
const shopid_yd = ref(null)
const pfrom = ref(0)
const leftListRef = ref(null)
const addOrEditRef = ref(null)
const detaillRef = ref(null)

// 新增活动
const isEdit = ref(false)
const addActivityList = () => {
	isEdit.value = true
	selectedIndex.value = null
	detailID.value = ''
	isDisbableInfo.value.type = false
	if (addOrEditRef.value) {
		isDisbableInfo.value.type = false
		addOrEditRef.value.restFun()
		addOrEditRef.value.objectForm.act = 'add'
		addOrEditRef.value.objectForm.status = 1
		addOrEditRef.value.objectForm.type = ''
		addOrEditRef.value.objectForm.title = ''
	}
}


// 状态切换
const handleClick = (e) => {
	selectedIndex.value = 0
	recordSelectedIndex.value = 0
	box_index_key.value = box_list_arr.value[e.index].name
	isDisbableInfo.value.index_key = box_index_key.value
	// 状态 1未开始 2进行中 3已失效
	if (box_index_key.value == '-1') {
		isEdit.value = false
	} else {
		isEdit.value = true
	}
	// if (box_index_key.value == '1') {
	// 	isDisbableInfo.value.type = false
	// } else {
	// 	isDisbableInfo.value.type = true
	// }
	// 移除refreshFun()调用，避免不必要的重置
	getEventLs(true)
}

const refreshFun = () => {
	lNoMore.value = false
	lLoading.value = false
	pfrom.value = 0
	detailID.value = ''
	listData.value = []
}

// 选择分店
const selectFun = (e) => {
	getEventLs(true)
}

const loadFun = () => {
	if (lNoMore.value) return
	proxy.$nextTick(() => {
		pfrom.value += 20
		getEventLs(false)
	})
}

const getEventLs = async (t = true) => {
	lLoading.value = true
	// 防止重复请求
	if (lLoading.value && !t) return
	// type  是否刷新列表
	if (t == true) {
		pfrom.value = 0
		listData.value = []
	}
	let param = {
		shopid_yd: shopid_yd.value,
		pnum: maxPnum,
		pfrom: pfrom.value,
		stime: "",
		dtime: "",
		time: time.value,
		st: box_index_key.value == '-1' ? '2' : box_index_key.value,
	}

	let url = config.yx_qd_event_ls
	if (box_index_key.value == '-1' || box_index_key.value == '1') {
		url = config.yx_qd_event_ls
		param.status = statusSt.value
	} else {
		url = config.yx_qd_log_ls
	}
	try {
		let res = await proxy.$api({
			url,
			data: param
		})
		lLoading.value = false
		if (res.status == 1) {
			let result = res.data
			if (box_index_key.value == '-1') {
				getStatusList.value = result.status_ls.map(item => ({
					id: item.id,
					name: item.title,
				}))
			}
			if (result.ls) {
				listData.value.push(...result.ls)
				// 确保索引在有效范围内
				const validIndex = Math.min(selectedIndex.value, listData.value.length - 1)
				detailID.value = listData.value[validIndex]?.id
				if (box_index_key.value == '-1') {
					jf_total.value = result.jf_total
				}
				if (box_index_key.value == '2') {
					detailGiveObj.value = listData.value[validIndex]
				}
				if (result.ls.length < maxPnum) {
					lNoMore.value = true
				} else {
					lNoMore.value = false
				}
			} else {
				lNoMore.value = true;
			}
		} else {
			lNoMore.value = true
		}
	} catch (error) {
		lLoading.value = false
		lNoMore.value = true
	} finally {
		lLoading.value = false
	}
}

//  获取积分类型列表
const typeLsSys = ref([])
const getFractTypeLs = async () => {
	let param = {
		ch: 1,
		is_sys: false,
	}
	let res = await proxy.$api({
		url: config.yx_jf_fract_type_ls,
		data: param
	})
	if (res.status == 1) {
		typeLsSys.value = res.data?.type_ls_sys.map(item => ({
			id: item.id,
			name: item.title,
		}))
	}
}
getFractTypeLs()
//  获取云店列表
const getYunShopLsFun = async () => {
	let param = {}
	try {
		let res = await proxy.$api({
			url: config.YUN_SHOP_LS,
			data: param
		})
		if (res.status == 1) {
			getYunShopList.value.push(...res.data)
			shopid_yd.value = res.data[0].id
			getYunShopSeleteList.value = res.data
		}
	} catch (error) { }
}

const addTpBmFun = (e) => {
	box_index_key.value = e?.status?.toString()
	isDisbableInfo.value.index_key = e?.status?.toString()
	isEdit.value = true
	if (e.type == 'add' || e.type == 'del' || e.type == 'edt') {
		selectedIndex.value = 0
		refreshFun()
		getEventLs(true)
	} else if (e.type == 'edt') {
		selectedIndex.value = recordSelectedIndex.value
		detailID.value = listData.value[recordSelectedIndex.value].id
		getEventLs(true)
	} else {
		selectedIndex.value = recordSelectedIndex.value
		detailID.value = listData.value[recordSelectedIndex.value].id
	}
}

const detailGiveObj = ref({})
const clickItem = (index) => {
	isEdit.value = true
	selectedIndex.value = index
	recordSelectedIndex.value = index
	detailID.value = listData.value[index].id
	addOrEditRef.value.objectForm.act = 'edt'
}

const clickEventLsItem = (index) => {
	selectedIndex.value = index
	recordSelectedIndex.value = index
	detailGiveObj.value = listData.value[index]
	detailID.value = listData.value[index].id
}

const backFun = (e) => {
	console.log("e=", e)
	if (e == 'back') {
		if (box_index_key.value == '-1') {
			isEdit.value = false
		} else {
			isEdit.value = true
		}
		selectedIndex.value = recordSelectedIndex.value
		detailID.value = listData.value[recordSelectedIndex.value].id
	}
}

// 正确使用 watch
watch(() => selectedIndex.value, (newValue) => {
	console.log("newValue=", newValue)
	// if (newValue == null) {
	//     detailID.value = ''
	//     return
	// }
	// if (newValue) {
	//     selectedIndex.value = newValue
	// }
	// if (listData.value && listData.value.length > 0) {
	//     // 确保索引在有效范围内
	//     const validIndex = Math.min(newValue, listData.value.length - 1)
	//     const selectedItem = listData.value[validIndex]
	//     if (selectedItem && selectedItem.id) {
	//         detailID.value = selectedItem.id
	//     } else {
	//         detailID.value = ''
	//     }
	// } else {
	//     detailID.value = ''
	// }
}, {
	immediate: true
})

// 活动记录
const activityList = (row) => {
	// TODO: Implement activity list functionality
}

onMounted(async () => {
	await getYunShopLsFun()
	getEventLs(true)
})
</script>

<style lang="scss" scoped>
div {
	box-sizing: border-box;
}

.board-box {
	box-sizing: border-box;
	height: 130px;
	background-color: #e22a2a;
	border-radius: 10px;
	padding: 10px 20px;
	color: #fff;
}

.activity-list {

	.left-box,
	.rigth-box {
		width: 100%;
		padding: 10px 10px 0 10px;
		height: 100vh;
		position: relative;
		border-right: 1px solid #e6e6e6;

		.iconBox {
			position: absolute;
			top: 0px;
			right: 13px;
			font-size: 26px;
			cursor: pointer;

			.search-icon {
				font-size: 20px;
				color: #333;
			}
		}

		.marketing-add {
			width: 100%;
		}
	}

	.status_txt {
		position: absolute;
		right: 20px;
		top: 33px;
	}

	.list_btn {
		position: absolute;
		bottom: 10px;
		right: 20px;
		z-index: 9;
	}
}

.ellipsis2 {
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.left-box {
	.select-w {
		width: 49%;
	}
}

.total-give {
	border-top: 1px solid #e6e6e6;
	padding-top: 10px;
	margin-top: 10px;
}
</style>